<?php

namespace App\Jobs\Stats\Platform\Settlement;

use App\Jobs\Stats\Stats as JobStats;
use App\Models\Admin\Stats\Platform\Settlement\Day as Stats;
use App\Models\Game\Settlement\Info;

class Day extends JobStats
{

    /**
     * 执行统计任务。
     *
     * @return void
     */
    public function stats()
    {
        $rate = $this->task->org->config->rate;
        $platCodes = $this->task->org->orgs()->pluck('code')->toArray();

        $columns[] = 'currency';
        $columns[] = 'SUM(bet_num) as bet_num';
        $columns[] = 'SUM(gain_player) as gain_player';
        $columns[] = "CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})) AS usd_bet_num";
        $columns[] = "CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})) AS usd_gain_player";

        $stats = Info::dbTable()->selectRaw(implode(',', $columns))
            ->where('status', Info::STATUS_NORMAL)
            ->where('player_type', Info::PLAYER_TYPE)
            ->where('end_time', '<', $this->task->timed + 86400)
            ->where('end_time', '>=', $this->task->timed)
            ->whereIn('plat_code', $platCodes)
            ->groupBy('currency')
            ->get();

        $stats->each(function ($item) use ($rate) {
            Stats::updateOrCreate(
                $this->task->only(['timed', 'plat_code']) + ['currency' => $item['currency']],
                [
                    'rate' => $rate,
                    'bet_num' => $item['bet_num'], 'amount' => -$item['gain_player'],
                    'revenue' => $this->makeRound((-$item['gain_player']) * $rate),
                    'usd' => [
                        'bet_num' => $this->makeRound($item['usd_bet_num']),
                        'amount' => $this->makeRound(-$item['usd_gain_player']),
                        'revenue' => $this->makeRound((-$item['usd_gain_player']) * $rate),
                    ]
                ]
            );
        });
    }
}
